<?php

/**
 * Created by PhpStorm.
 * User: TC
 * Date: 2015/10/22
 * Time: 15:34
 */
class connectDB
{
    private static $_instance;

    private $_MongoDB;
    private $_MongoClient;

    private function __construct() {
        if($this->_MongoDB == null) {
            var_dump('new db');
            $dbname = 'test';
            $host = '127.0.0.1';
            $port = 27017;
            $userName = 'tc';
            $pwd = 'tc199286196988';
            try {
                $this->_MongoClient = new MongoClient("mongodb://$host:$port");
                $this->_MongoDB = $this->_MongoClient->selectDB($dbname);
                $this->_MongoDB->authenticate($userName, $pwd);
            } catch(MongoConnectionException $e) {}
        }
    }

    public function __unconstruct(){
        $this->_MongoClient->close();
        $this->_MongoDB = null;
        $this->_MongoClient = null;
        unset($this->_MongoClient);
        unset($this->_MongoDB);
    }

    private function __clone(){}

    public static function getInstance() {
        if(self::$_instance == null) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function openDB() {
        if($this->_MongoDB == null) {
            var_dump('new db');
            $dbname = 'test';
            $host = '127.0.0.1';
            $port = 27017;
            $userName = 'tc';
            $pwd = 'tc199286196988';
            try {
                $this->_MongoClient = new MongoClient("mongodb://$host:$port");
                $this->_MongoDB = $this->_MongoClient->selectDB($dbname);
                $this->_MongoDB->authenticate($userName, $pwd);
            } catch(MongoConnectionException $e) {
                return 801;
            }
        }
        return $this->_MongoDB;
    }

    public function closeDB() {
        $this->_MongoClient->close();
        $this->_MongoClient = null;
        $this->_MongoDB = null;
        unset($this->_MongoClient);
        unset($this->_MongoDB);
    }
}